package tech.jabari.user.controller;

import org.omg.CORBA.OBJECT_NOT_EXIST;
import tech.jabari.constants.UMSConstant;
import tech.jabari.utils.JdbcUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import static tech.jabari.constants.UMSConstant.USER_ID;
import static tech.jabari.constants.UMSConstant.WELCOME_URL_KEY;

/**
 * @author Jabari Lu
 * @title: UserLogin
 * @data 2020/7/30 14:20
 */
@WebServlet("/userLogin")
public class UserLogin extends HttpServlet {


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 登录的逻辑处理
        //1. 获取用户名、密码
        //2.根据用户名、密码到数据库查询  ：
        // select * from t_user where username=? and pwd = ?

        /*resp.getWriter().write("<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <title>welcome</title>\n" +
                "</head>\n" +
                "<body>\n" +
                "    <h1>恭喜，登录成功！</h1>\n" +
                "\n" +
                "    <img src=\"img/welcome.jpg\" height=\"366\" width=\"524\"/>\n" +
                "</body>\n" +
                "</html>！");*/
        // 响应的重定向
        // 如果登录成功，跳转到welcome.html。

        // 如果失败的话，回到login.html，提示:用户名或密码错误。

        String username = req.getParameter("username");
        String pwd = req.getParameter("pwd");
        List queryList = JdbcUtil.query
                ("select * from t_user where username=? and pwd=?",username,pwd);
        if (null != queryList && queryList.size() > 0){
            String key = UMSConstant.WELCOME_CAN_ACCESS; // accessWelcome表示可以访问：欢迎页面。
            HttpSession session = req.getSession();
            session.setAttribute(WELCOME_URL_KEY,key);// 将可以访问的key，放入到session中。
            //将用户id放入到session中
            Map<String, Object> userMap = (Map<String,Object>)queryList.get(0);
            String id = ((Integer) userMap.get("id")).toString();
            session.setAttribute(USER_ID, id);
            resp.sendRedirect("/welcome.action");
        }else {
            resp.sendRedirect("/login.html?error=111");
        }
    }
}
